package dao;

import util.MybatisUtils;
import mapper.UserMapper;
import org.apache.ibatis.session.SqlSession;
import pojo.User;

import java.util.List;

//调用数据库的方法
public class UserDao {

    /**
     * 查询所有用户列表
     */
    public List<User> getUserList() {
        //创建SQL对象
        SqlSession sqlSession = MybatisUtils.getSqlSession();
        //调用getMapper方法                            //这里填对应的Mapper类
        UserMapper userService = sqlSession.getMapper(UserMapper.class);
        //返回查询结果
        List<User> list = userService.getUserList();

        sqlSession.close();
        return list;
    }

    /**
     * 根据id查询用户信息
     */
    public User getUserListById(String id) {
        //创建SQL对象
        SqlSession sqlSession = MybatisUtils.getSqlSession();
        //调用getMapper方法                            //这里填对应的Mapper类
        UserMapper userService = sqlSession.getMapper(UserMapper.class);
        User user = userService.selectById(id);
        //返回查询结果
        sqlSession.close();
        return user;
    }

    public boolean checkLogin(String id, String password) {
        //创建SQL对象
        SqlSession sqlSession = MybatisUtils.getSqlSession();
        //调用getMapper方法                            //这里填对应的Mapper类
        UserMapper userService = sqlSession.getMapper(UserMapper.class);
        boolean b = false;
        User user = userService.loginCheck(id, password);
        if (user != null) {
            b = true;
        }
        sqlSession.close();
        return b;
    }

    public void addNewUser(User user) {
        //创建SQL对象
        SqlSession sqlSession = MybatisUtils.getSqlSession();
        //调用getMapper方法                            //这里填对应的Mapper类
        UserMapper userService = sqlSession.getMapper(UserMapper.class);
        userService.addNewUser(user);
        sqlSession.commit();
        sqlSession.close();
    }

    public boolean checkNick(String nick){
        //创建SQL对象
        SqlSession sqlSession = MybatisUtils.getSqlSession();
        //调用getMapper方法                            //这里填对应的Mapper类
        UserMapper userService = sqlSession.getMapper(UserMapper.class);
        boolean b = false;
        String theNick = userService.nickCheck(nick);
        if(theNick!=null){
            b=true;
        }
        sqlSession.close();
        return b;
    }

    public void resetPassword(String email, String password) {
        //创建SQL对象
        SqlSession sqlSession = MybatisUtils.getSqlSession();
        //调用getMapper方法                            //这里填对应的Mapper类
        UserMapper userService = sqlSession.getMapper(UserMapper.class);
        userService.resetPassword(email,password);
        sqlSession.commit();
        sqlSession.close();
    }
}
